package com.copd.service.impl;

import com.copd.dto.PatientCreateRequest;
import com.copd.dto.PatientUpdateRequest;
import com.copd.entity.Patient;
import com.copd.mapper.PatientMapper;
import com.copd.service.DataBackupService;
import com.copd.service.DoctorOperationLogService;
import com.copd.service.PatientService;
import com.copd.util.PatientOperationLogger;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashSet;
import java.util.Set;

@Service
public class PatientServiceImpl implements PatientService {
    private static final Logger logger = LoggerFactory.getLogger(PatientServiceImpl.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();
    
    @Autowired
    private PatientMapper patientMapper;
    
    @Autowired
    private DoctorOperationLogService logService;
    
    @Autowired
    private DataBackupService dataBackupService;
    
    @Autowired
    private PatientOperationLogger operationLogger;

    @Override
    public Patient getPatientById(int id) {
        List<Patient> patients = patientMapper.selectAllPatients(id, null, null, null, null, null, 0, 1);
        if (patients == null || patients.isEmpty()) {
            return null;
        }
        
        // 记录查看患者操作日志
        try {
            Integer doctorId = getCurrentDoctorId();
            if (doctorId != null) {
                String ipAddress = "";
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes != null) {
                    HttpServletRequest request = attributes.getRequest();
                    ipAddress = getClientIpAddress(request);
                }
                // 记录查询操作
                operationLogger.logPatientQuery(doctorId, id, ipAddress);
            }
        } catch (Exception e) {
            // 记录日志失败不影响正常业务
            logger.error("记录查询患者操作日志失败", e);
        }
        
        return patients.get(0);
    }

    @Override
    public void createPatient(String name) {
        Patient patient = new Patient();
        patient.setName(name);
        patientMapper.insertPatient(patient);
        
        // 记录创建患者操作日志
        try {
            Integer doctorId = getCurrentDoctorId();
            if (doctorId != null) {
                String ipAddress = "";
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes != null) {
                    HttpServletRequest requestObj = attributes.getRequest();
                    ipAddress = getClientIpAddress(requestObj);
                }
                
                // 创建一个基本的请求对象
                PatientCreateRequest simpleRequest = new PatientCreateRequest();
                PatientCreateRequest.BasicInfo basicInfo = new PatientCreateRequest.BasicInfo();
                basicInfo.setName(name);
                simpleRequest.setBasicInfo(basicInfo);
                
                // 记录操作日志和备份
                operationLogger.logPatientCreate(doctorId, patient.getPatientId(), simpleRequest, ipAddress);
            }
        } catch (Exception e) {
            // 记录日志失败不影响正常业务
            logger.error("记录创建患者操作日志失败", e);
        }
    }

    @Override
    @Transactional
    public Integer createPatient(PatientCreateRequest request) {
        // 1. 验证基本信息
        validateBasicInfo(request);
        
        // 2. 验证诊断记录
        validateDiagnosisRecords(request);
        
        // 3. 验证检查项目
        validateExaminationItems(request);
        
        // 4. 验证治疗项目
        validateTreatmentPlans(request);
        
        // 5. 验证出院建议
        validateDischargeAdvices(request);

        try {
            // 6. 创建患者基本信息
            Patient patient = new Patient();
            PatientCreateRequest.BasicInfo basicInfo = request.getBasicInfo();
            patient.setUserId(basicInfo.getUserId());
            patient.setName(basicInfo.getName());
            patient.setGender(basicInfo.getGender());
            patient.setAge(basicInfo.getAge());
            patient.setDepartment(basicInfo.getDepartment());
            patient.setHospitalizationNumber(basicInfo.getHospitalizationNumber());
            
            // 转换LocalDateTime为Date
            Date now = Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());
            patient.setCreateTime(now);
            patient.setUpdateTime(now);
            
            // 7. 插入患者基本信息并获取ID
            patientMapper.insertPatient(patient);
            Integer patientId = patient.getPatientId();
            
            // 获取当前医生ID
            Integer doctorId = getCurrentDoctorId();
            
            // 8. 插入诊断记录
            if (request.getDiagnosisRecords() != null && !request.getDiagnosisRecords().isEmpty()) {
                for (PatientCreateRequest.DiagnosisRecord diagnosis : request.getDiagnosisRecords()) {
                    patientMapper.insertDiagnosisRecord(
                        patientId,
                        diagnosis.getDiagnosisItem(),
                        diagnosis.getDiagnosisContent(),
                        diagnosis.getRemarks()
                    );
                }
            }
            
            // 9. 插入检查项目
            if (request.getExaminationItems() != null && !request.getExaminationItems().isEmpty()) {
                for (PatientCreateRequest.ExaminationItem exam : request.getExaminationItems()) {
                    // 从完整名称中提取类别（取第一个逗号或空格之前的部分）
                    String examItem = exam.getExamItem();
                    String examCategory = extractCategory(examItem);
                    
                    patientMapper.insertExaminationItem(
                        patientId,
                        examCategory,
                        examItem,
                        exam.getExamResult(),
                        exam.getReferenceValue(),
                        exam.getRemarks()
                    );
                }
            }
            
            // 10. 插入治疗方案
            if (request.getTreatmentPlans() != null && !request.getTreatmentPlans().isEmpty()) {
                for (PatientCreateRequest.TreatmentPlan plan : request.getTreatmentPlans()) {
                    // 从完整名称中提取类别（取第一个逗号或空格之前的部分）
                    String treatmentItem = plan.getTreatmentItem();
                    String planCategory = extractCategory(treatmentItem);
                    
                    patientMapper.insertTreatmentPlan(
                        patientId,
                        planCategory,
                        treatmentItem,
                        plan.getSpecificPlan(),
                        plan.getRemarks()
                    );
                }
            }
            
            // 11. 插入出院建议
            if (request.getDischargeAdvices() != null && !request.getDischargeAdvices().isEmpty()) {
                for (PatientCreateRequest.DischargeAdvice advice : request.getDischargeAdvices()) {
                    // 从完整名称中提取类别（取第一个逗号或空格之前的部分）
                    String dischargeItem = advice.getDischargeItem();
                    String adviceCategory = extractCategory(dischargeItem);
                    
                    patientMapper.insertDischargeAdvice(
                        patientId,
                        adviceCategory,
                        dischargeItem,
                        advice.getDischargeContent(),
                        advice.getRemarks()
                    );
                }
            }
            
            // 12. 记录操作日志和备份数据
            String ipAddress = "";
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest httpRequest = attributes.getRequest();
                ipAddress = getClientIpAddress(httpRequest);
            }
            operationLogger.logPatientCreate(doctorId, patientId, request, ipAddress);
            
            return patientId;
        } catch (Exception e) {
            String errorMsg = "添加患者失败: " + e.getMessage();
            
            // 记录创建患者失败的日志
            try {
                Integer doctorId = getCurrentDoctorId();
                if (doctorId != null) {
                    PatientCreateRequest.BasicInfo basicInfo = request.getBasicInfo();
                    logPatientOperation(doctorId, null, "新增", false, errorMsg, 
                            "patient_info", null, "创建名为" + basicInfo.getName() + "的患者记录失败");
                }
            } catch (Exception logEx) {
                // 记录日志失败不影响正常业务
                logger.error("记录创建患者失败的操作日志失败", logEx);
            }
            
            throw new RuntimeException(errorMsg);
        }
    }

    private void validateBasicInfo(PatientCreateRequest request) {
        if (request.getBasicInfo() == null) {
            throw new RuntimeException("基本信息不能为空");
        }
        PatientCreateRequest.BasicInfo basicInfo = request.getBasicInfo();
        
        // 验证姓名
        if (!StringUtils.hasText(basicInfo.getName())) {
            throw new RuntimeException("患者姓名不能为空");
        }
        
        // 验证性别
        if (!StringUtils.hasText(basicInfo.getGender())) {
            throw new RuntimeException("患者性别不能为空");
        }
        
        // 验证年龄
        if (basicInfo.getAge() == null) {
            throw new RuntimeException("患者年龄不能为空");
        }
        if (basicInfo.getAge() < 0 || basicInfo.getAge() > 150) {
            throw new RuntimeException("患者年龄必须在0-150岁之间");
        }
        
        // 验证科室
        if (!StringUtils.hasText(basicInfo.getDepartment())) {
            throw new RuntimeException("科室不能为空");
        }
        
        // 验证住院号
        if (basicInfo.getHospitalizationNumber() == null) {
            throw new RuntimeException("住院号不能为空");
        }
        
        // 其他字段允许为空
    }

    private void validateDiagnosisRecords(PatientCreateRequest request) {
        if (request.getDiagnosisRecords() == null || request.getDiagnosisRecords().isEmpty()) {
            throw new RuntimeException("诊断记录不能为空");
        }
        for (int i = 0; i < request.getDiagnosisRecords().size(); i++) {
            PatientCreateRequest.DiagnosisRecord record = request.getDiagnosisRecords().get(i);
            if (!StringUtils.hasText(record.getDiagnosisItem())) {
                throw new RuntimeException("第" + (i + 1) + "条诊断记录的项目名称不能为空");
            }
            // 其他字段允许为空
        }
    }

    private void validateExaminationItems(PatientCreateRequest request) {
        if (request.getExaminationItems() == null || request.getExaminationItems().isEmpty()) {
            throw new RuntimeException("检查项目不能为空");
        }
        for (int i = 0; i < request.getExaminationItems().size(); i++) {
            PatientCreateRequest.ExaminationItem item = request.getExaminationItems().get(i);
            if (!StringUtils.hasText(item.getExamItem())) {
                throw new RuntimeException("第" + (i + 1) + "条检查项目的名称不能为空");
            }
            // 其他字段允许为空
        }
    }

    private void validateTreatmentPlans(PatientCreateRequest request) {
        if (request.getTreatmentPlans() == null || request.getTreatmentPlans().isEmpty()) {
            throw new RuntimeException("治疗计划不能为空");
        }
        for (int i = 0; i < request.getTreatmentPlans().size(); i++) {
            PatientCreateRequest.TreatmentPlan plan = request.getTreatmentPlans().get(i);
            if (!StringUtils.hasText(plan.getTreatmentItem())) {
                throw new RuntimeException("第" + (i + 1) + "条治疗计划的名称不能为空");
            }
            // 其他字段允许为空
        }
    }

    private void validateDischargeAdvices(PatientCreateRequest request) {
        if (request.getDischargeAdvices() == null || request.getDischargeAdvices().isEmpty()) {
            throw new RuntimeException("出院建议不能为空");
        }
        for (int i = 0; i < request.getDischargeAdvices().size(); i++) {
            PatientCreateRequest.DischargeAdvice advice = request.getDischargeAdvices().get(i);
            if (!StringUtils.hasText(advice.getDischargeItem())) {
                throw new RuntimeException("第" + (i + 1) + "条出院建议的名称不能为空");
            }
            // 其他字段允许为空
        }
    }

    @Override
    public List<Patient> getAllPatients(
        String name,
        String hospitalizationNumber,
        String department,
        String gender,
        Integer userId,
        int page,
        int size
    ) {
        int offset = (page - 1) * size;
        List<Patient> patients = patientMapper.selectAllPatients(
            null, // patientId
            name,
            hospitalizationNumber,
            department,
            gender,
            userId,
            offset,
            size
        );
        
        // 记录查询患者列表操作日志
        try {
            Integer doctorId = getCurrentDoctorId();
            if (doctorId != null) {
                String ipAddress = "";
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes != null) {
                    HttpServletRequest request = attributes.getRequest();
                    ipAddress = getClientIpAddress(request);
                }
                
                // 记录查询操作
                logPatientOperation(doctorId, null, "查询", true, null, 
                        "patient_info", null, "查询患者列表：姓名=" + name + 
                        ", 住院号=" + hospitalizationNumber + 
                        ", 科室=" + department + 
                        ", 性别=" + gender + 
                        ", 页码=" + page);
            }
        } catch (Exception e) {
            // 记录日志失败不影响正常业务
            logger.error("记录查询患者列表操作日志失败", e);
        }
        
        return patients;
    }

    @Override
    public long getTotalPatients(
        String name,
        String hospitalizationNumber,
        String department,
        String gender,
        Integer userId
    ) {
        return patientMapper.countPatients(
            name,
            hospitalizationNumber,
            department,
            gender,
            userId
        );
    }

    @Override
    @Transactional
    public boolean deletePatient(Integer patientId) {
        if (patientId == null) {
            throw new IllegalArgumentException("患者ID不能为空");
        }
        
        // 获取医生ID
        Integer doctorId = getCurrentDoctorId();
        
        try {
            // 记录删除操作
            String ipAddress = "";
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                ipAddress = getClientIpAddress(request);
            }
            operationLogger.logPatientDelete(doctorId, patientId, ipAddress);
            
            // 删除相关数据
            // 1. 删除医生操作日志
            logService.deletePatientOperationLogs(patientId);
            
            // 2. 删除诊断记录
            patientMapper.deleteDiagnosisRecords(patientId);
            
            // 3. 删除检查项目
            patientMapper.deleteExaminationItems(patientId);
            
            // 4. 删除治疗方案
            patientMapper.deleteTreatmentPlans(patientId);
            
            // 5. 删除出院建议
            patientMapper.deleteDischargeAdvices(patientId);
            
            // 6. 最后删除患者基本信息
            int result = patientMapper.deletePatient(patientId);
            boolean success = result > 0;
            
            // 记录删除操作日志
            logPatientOperation(doctorId, patientId, "删除", success, success ? null : "删除患者数据失败", 
                    "patient_info", patientId, "删除患者ID为" + patientId + "的所有数据");
            
            return success;
        } catch (Exception e) {
            logger.error("删除患者失败", e);
            
            // 记录删除失败日志
            logPatientOperation(doctorId, patientId, "删除", false, e.getMessage(), 
                    "patient_info", patientId, "删除患者ID为" + patientId + "的数据时发生异常");
            
            throw new RuntimeException("删除患者失败: " + e.getMessage());
        }
    }

    @Override
    public Map<String, Object> getPatientDetail(int patientId) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取医生ID
        Integer doctorId = getCurrentDoctorId();
        
        // 记录查询操作
        String ipAddress = "";
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            ipAddress = getClientIpAddress(request);
        }
        operationLogger.logPatientQuery(doctorId, patientId, ipAddress);
        
        // 获取患者基本信息
        Patient patient = getPatientById(patientId);
        if (patient == null) {
            throw new RuntimeException("未找到ID为" + patientId + "的患者");
        }
        
        result.put("basicInfo", patient);
        
        // 获取诊断记录
        List<Map<String, Object>> diagnosisRecords = patientMapper.selectDiagnosisRecords(patientId);
        result.put("diagnosisRecords", diagnosisRecords);
        
        // 获取检查项目
        List<Map<String, Object>> examinationItems = patientMapper.selectExaminationItems(patientId);
        result.put("examinationItems", examinationItems);
        
        // 获取治疗方案
        List<Map<String, Object>> treatmentPlans = patientMapper.selectTreatmentPlans(patientId);
        result.put("treatmentPlans", treatmentPlans);
        
        // 获取出院建议
        List<Map<String, Object>> dischargeRecords = patientMapper.selectDischargeRecords(patientId);
        result.put("dischargeRecords", dischargeRecords);
        
        return result;
    }

    @Override
    @Transactional
    public boolean updatePatient(PatientUpdateRequest request) {
        // 验证请求参数
        if (request == null || request.getPatientId() == null) {
            throw new IllegalArgumentException("患者ID不能为空");
        }
        
        // 获取医生ID
        Integer doctorId = getCurrentDoctorId();
        Integer patientId = request.getPatientId();
        
        try {
            // 1. 更新患者基本信息（如果提供了）
            if (request.getBasicInfo() != null) {
                patientMapper.updatePatientInfo(
                    request.getPatientId(),
                    request.getBasicInfo().getName(),
                    request.getBasicInfo().getGender(),
                    request.getBasicInfo().getAge(),
                    request.getBasicInfo().getDepartment(),
                    request.getBasicInfo().getHospitalizationNumber()
                );
            }
            
            // 2. 删除并重新插入诊断记录
            // 删除所有现有的诊断记录
            patientMapper.deleteDiagnosisRecords(patientId);
            
            // 插入新的诊断记录
            if (request.getDiagnosisRecords() != null && !request.getDiagnosisRecords().isEmpty()) {
                for (PatientUpdateRequest.DiagnosisRecord diagnosis : request.getDiagnosisRecords()) {
                    patientMapper.insertDiagnosisRecord(
                        patientId,
                        diagnosis.getDiagnosisItem(),
                        diagnosis.getDiagnosisContent(),
                        diagnosis.getRemarks()
                    );
                }
            }
            
            // 3. 删除并重新插入检查项目
            // 删除所有现有的检查项目
            patientMapper.deleteExaminationItems(patientId);
            
            // 插入新的检查项目
            if (request.getExaminationItems() != null && !request.getExaminationItems().isEmpty()) {
                for (PatientUpdateRequest.ExaminationItem exam : request.getExaminationItems()) {
                    // 从完整名称中提取类别（取第一个逗号或空格之前的部分）
                    String examItem = exam.getExamItem();
                    String examCategory = extractCategory(examItem);
                    
                    patientMapper.insertExaminationItem(
                        patientId,
                        examCategory,
                        examItem,
                        exam.getExamResult(),
                        exam.getReferenceValue(),
                        exam.getRemarks()
                    );
                }
            }
            
            // 4. 删除并重新插入治疗方案
            // 删除所有现有的治疗方案
            patientMapper.deleteTreatmentPlans(patientId);
            
            // 插入新的治疗方案
            if (request.getTreatmentPlans() != null && !request.getTreatmentPlans().isEmpty()) {
                for (PatientUpdateRequest.TreatmentPlan plan : request.getTreatmentPlans()) {
                    // 从完整名称中提取类别（取第一个逗号或空格之前的部分）
                    String treatmentItem = plan.getTreatmentItem();
                    String planCategory = extractCategory(treatmentItem);
                    
                    patientMapper.insertTreatmentPlan(
                        patientId,
                        planCategory,
                        treatmentItem,
                        plan.getSpecificPlan(),
                        plan.getRemarks()
                    );
                }
            }
            
            // 5. 删除并重新插入出院建议
            // 删除所有现有的出院建议
            patientMapper.deleteDischargeAdvices(patientId);
            
            // 插入新的出院建议
            if (request.getDischargeAdvices() != null && !request.getDischargeAdvices().isEmpty()) {
                for (PatientUpdateRequest.DischargeAdvice advice : request.getDischargeAdvices()) {
                    // 从完整名称中提取类别（取第一个逗号或空格之前的部分）
                    String dischargeItem = advice.getDischargeItem();
                    String adviceCategory = extractCategory(dischargeItem);
                    
                    patientMapper.insertDischargeAdvice(
                        patientId,
                        adviceCategory,
                        dischargeItem,
                        advice.getDischargeContent(),
                        advice.getRemarks()
                    );
                }
            }
            
            // 6. 记录更新操作和备份数据
            String ipAddress = "";
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest httpRequest = attributes.getRequest();
                ipAddress = getClientIpAddress(httpRequest);
            }
            operationLogger.logPatientUpdate(doctorId, patientId, request, ipAddress);
            
            return true;
        } catch (Exception e) {
            logger.error("更新患者信息失败", e);
            
            // 记录更新失败日志
            try {
                logPatientOperation(
                    doctorId, 
                    patientId, 
                    "修改", 
                    false, 
                    e.getMessage(), 
                    "patient_info", 
                    patientId, 
                    "更新患者ID为" + patientId + "的信息失败"
                );
            } catch (Exception logEx) {
                logger.error("记录更新失败日志出错", logEx);
            }
            
            throw new RuntimeException("更新患者信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 从请求上下文中获取当前医生ID
     * 实际项目中通常从会话或Token中获取当前登录用户
     */
    private Integer getCurrentDoctorId() {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                Object doctorIdObj = request.getAttribute("doctorId");
                if (doctorIdObj != null) {
                    return (Integer) doctorIdObj;
                }
                
                // 如果请求属性中没有，可以从会话或认证信息中获取
                // 这里使用默认值，实际项目中应根据认证机制获取
                return 1; // 默认医生ID
            }
        } catch (Exception e) {
            logger.error("获取当前医生ID失败", e);
        }
        return null;
    }
    
    /**
     * 记录患者操作日志
     */
    private void logPatientOperation(
            Integer doctorId, 
            Integer patientId, 
            String operationType, 
            boolean isSuccess, 
            String failureReason,
            String tableName,
            Integer recordId,
            String detail) {
        
        try {
            // 获取IP和设备信息
            String ipAddress = "";
            String deviceInfo = ""; // 添加设备信息
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                
                // 获取IP地址
                ipAddress = getClientIpAddress(request);
                // 获取设备信息
                deviceInfo = request.getHeader("User-Agent");
            }
            
            // 调用日志服务记录操作
            logService.logPatientOperation(
                doctorId,
                patientId,
                operationType,
                ipAddress,
                deviceInfo,
                isSuccess,
                failureReason,
                tableName,
                recordId,
                detail
            );
        } catch (Exception e) {
            logger.error("记录操作日志失败", e);
        }
    }
    
    /**
     * 获取客户端的IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    
    /**
     * 从字符串中提取类别（取第一个逗号或空格之前的部分）
     */
    private String extractCategory(String fullString) {
        if (fullString == null || fullString.isEmpty()) {
            return "";
        }
        
        // 尝试按逗号分割
        int commaIndex = fullString.indexOf('，');
        if (commaIndex == -1) {
            commaIndex = fullString.indexOf(',');
        }
        
        // 如果没有逗号，尝试按空格分割
        if (commaIndex == -1) {
            int spaceIndex = fullString.indexOf(' ');
            if (spaceIndex != -1) {
                return fullString.substring(0, spaceIndex);
            }
        } else {
            return fullString.substring(0, commaIndex);
        }
        
        // 如果没有逗号或空格，返回整个字符串
        return fullString;
    }
}